import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import Vue from 'vue'

// create an axios instance
const service = axios.create({
  baseURL: window.SITE_CONFIG.baseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const method = response.config.method
    const res = response.data
    if (res.code === 200 && (method !== 'get')) {
      Message({
        message: res.message || 'success',
        type: 'success',
        duration: 2 * 1000
      })
    }
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
